package dao

import (
	"errors"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"strconv"
	"znzc_monitor/configs"
	"znzc_monitor/configs/configEntity"
	"znzc_monitor/domain"
	_ "znzc_monitor/domain"
)

func OpenDataBases() (*sqlx.DB, error) {

	configInfo := configs.GetDatabaseInfo()
	log.Println("数据库连接信息为：", configInfo)

	d := DataBases(configInfo)

	var dataSourceName = d.User + ":" + d.Password + "@tcp(" + d.Host + ":" + strconv.Itoa(d.Port) + ")/" + d.Name

	//database, err := sqlx.Open("数据库类型", "用户名:密码@tcp(地址:端口)/数据库名")
	database, err := sqlx.Open("mysql", dataSourceName)

	if err != nil {
		log.Println("数据库连接失败！")
		return nil, errors.New("发布失败！")
	}

	log.Println("数据库连接成功！")

	return database, err

}

func SelectInfo(Db *sqlx.DB) []domain.Server {

	var servers []domain.Server
	err := Db.Select(&servers, "SELECT s.id,s.ip,s.name,s.last_connect_time,s.max_task_num FROM `server` s")
	if err != nil {
		log.Println("查询主机配置信息失败：", err)
		return nil
	}
	log.Println("查询主机配置信息成功，结果为：", servers)

	return servers

}

func SelectOneByIp(Db *sqlx.DB, ip string) *domain.Server {

	var server domain.Server
	err := Db.Get(&server, "SELECT s.id,s.ip,s.name,s.last_connect_time,s.max_task_num FROM `server` s where s.ip=?", ip)
	if err != nil {
		log.Println("查询主机配置信息失败：", err)
		return nil
	}
	log.Println("查询主机配置信息成功，结果为：", server)
	return &server

}

func DataBases(configInfo map[string]interface{}) *configEntity.DataBases {

	d := new(configEntity.DataBases)

	if value, ok := configInfo["name"].(string); ok {
		d.Name = value
	}

	if value, ok := configInfo["host"].(string); ok {
		d.Host = value
	}

	if value, ok := configInfo["user"].(string); ok {
		d.User = value
	}

	if value, ok := configInfo["password"].(string); ok {
		d.Password = value
	}

	if value, ok := configInfo["port"].(int); ok {
		d.Port = value
	}

	return d

}
